# -*- coding: utf-8 -*-

import os,pyperclip,json,login,time,requests

from PyQt5 import QtCore,QtWidgets
from PyQt5.QtGui import QBrush, QColor
from PyQt5.QtWidgets import *
import pandas as pd

from dbbaishi import MysqlDBHandler

from call_select import call_select_dialog
from user_setting import user_setting_dialog
from user_setting import alert_dialog

from apscheduler.schedulers.background import BackgroundScheduler

class Ui_Model_Window(QtWidgets.QMainWindow):

    def __init__(self):
        super(Ui_Model_Window,self).__init__()
        user_file = os.path.exists("./userinfo.json")
        self.db = MysqlDBHandler()
        self.all_header_combobox=[]
        self.user_data=None
        self.tickt_data = None
        self.backend = None
        self.thread = None

        if user_file:
            with open("./userinfo.json","r",encoding="utf-8")as f:
                self.user_info = json.loads(f.read())
        else:
            self.user_info = {}

        self.setupUi(self)
        self.scheduler = BackgroundScheduler()
        try:
            self.scheduler.remove_job("dialog")
        except:
            pass
        self.scheduler.add_job(self.showDialog, 'interval', id="dialog", seconds=5)
        self.scheduler.start()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(980, 600)   #872, 493
        # MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        MainWindow.setMinimumSize(QtCore.QSize(0, 0))
        MainWindow.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralWidget)
        self.verticalLayout.setObjectName("verticalLayout")  # 总体布局
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()  # 第一行布局
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.lineEdit = QtWidgets.QLineEdit(self.centralWidget)
        self.lineEdit.setObjectName("lineEdit")  # 空白框
        self.horizontalLayout_2.addWidget(self.lineEdit)
        self.pushButton_2 = QtWidgets.QPushButton(self.centralWidget)
        self.pushButton_2.setObjectName("pushButton_2")  # 导入
        self.horizontalLayout_2.addWidget(self.pushButton_2)
        self.comboBox_2 = QtWidgets.QComboBox(self.centralWidget)
        self.comboBox_2.setObjectName("comboBox_2")  # 用户名----验证信息
        self.horizontalLayout_2.addWidget(self.comboBox_2)
        self.comboBox_3 = QtWidgets.QComboBox(self.centralWidget)
        self.comboBox_3.setObjectName("comboBox_3")  # 站点
        self.horizontalLayout_2.addWidget(self.comboBox_3)
        self.horizontalLayout_2.setStretch(0, 5)  # 空白框    setStretch：设置同一布局里的比例 （第几个元素，比例）
        self.horizontalLayout_2.setStretch(1, 1)  # 导入
        self.horizontalLayout_2.setStretch(2, 3)  # 用户名
        self.horizontalLayout_2.setStretch(3, 3)  # 站点
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")  # 第二行布局
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Minimum)  # 第一个弹簧效果：空隙
        self.horizontalLayout.addItem(spacerItem)
        self.label = QtWidgets.QLabel(self.centralWidget)  # 开始时间
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.dateEdit = QtWidgets.QDateEdit(QtCore.QDate.currentDate(), self)  # 第一个时间控件
        self.dateEdit.setDisplayFormat("yyyy-MM-dd")
        self.dateEdit.setObjectName("dateEdit")
        self.horizontalLayout.addWidget(self.dateEdit)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Minimum)  # 第二个弹簧效果：空隙
        self.horizontalLayout.addItem(spacerItem1)
        self.label_5 = QtWidgets.QLabel(self.centralWidget)
        self.label_5.setObjectName("label_5")  # 结束时间
        self.horizontalLayout.addWidget(self.label_5)
        self.dateEdit_2 = QtWidgets.QDateEdit(QtCore.QDate.currentDate(), self)  # 第二个时间控件
        self.dateEdit_2.setObjectName("dateEdit_2")
        self.dateEdit_2.setDisplayFormat("yyyy-MM-dd")
        self.horizontalLayout.addWidget(self.dateEdit_2)
        spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Minimum)  # 第三个弹簧效果：空隙
        self.horizontalLayout.addItem(spacerItem2)
        self.label_3 = QtWidgets.QLabel(self.centralWidget)
        self.label_3.setObjectName("label_3")  # 单号
        self.horizontalLayout.addWidget(self.label_3)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralWidget)  # 填空框
        self.lineEdit_3.setMinimumSize(QtCore.QSize(150, 0))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.horizontalLayout.addWidget(self.lineEdit_3)
        spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Minimum)  # 第四个弹簧效果：空隙
        self.horizontalLayout.addItem(spacerItem3)
        self.label_6 = QtWidgets.QLabel(self.centralWidget)  # 人工跟进状态
        self.label_6.setObjectName("label_6")
        self.horizontalLayout.addWidget(self.label_6)
        self.comboBox_5 = QtWidgets.QComboBox(self.centralWidget)  # 跟进选择框
        self.comboBox_5.setObjectName("comboBox_5")
        self.horizontalLayout.addWidget(self.comboBox_5)
        self.label_2 = QtWidgets.QLabel(self.centralWidget)  # 录入组
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.comboBox_4 = QtWidgets.QComboBox(self.centralWidget)  # 组别选择框
        self.comboBox_4.setObjectName("comboBox_4")
        self.horizontalLayout.addWidget(self.comboBox_4)
        self.label_4 = QtWidgets.QLabel(self.centralWidget)  # 状态
        self.label_4.setObjectName("label_4")
        self.horizontalLayout.addWidget(self.label_4)
        self.comboBox = QtWidgets.QComboBox(self.centralWidget)  # 完成状态选择框
        self.comboBox.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.comboBox.setObjectName("comboBox")
        self.horizontalLayout.addWidget(self.comboBox)
        self.pushButton = QtWidgets.QPushButton(self.centralWidget)  # 查询按钮
        self.pushButton.setMaximumSize(QtCore.QSize(16777215, 24))
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.tableWidget = QtWidgets.QTableWidget(self.centralWidget)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(25)  # 定义列 #diyigexiugai
        self.tableWidget.setRowCount(5)  # 定义行
        self.tableWidget.horizontalHeader().setVisible(False)  # 列标题不可见
        self.tableWidget.verticalHeader().setVisible(False)#行标题不可见
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 不可编辑
        # self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) #选择一行
        # self.tableWidget.setShowGrid(False) #网格线不可见、
        # 合并单元格
        self.tableWidget.setRowHeight(0, 20)  # 第0行高度
        self.tableWidget.setRowHeight(1, 20)  # 第1行高度
        self.tableWidget.setSpan(0, 0, 2, 1)  # //第一个参数：要改变的单元格行//第二个参数：要改变的单元格列数//第三个参数：需要合并的行数//第四个参数：需要合并的列数
        self.tableWidget.setSpan(0, 1, 2, 1)
        self.tableWidget.setSpan(0, 2, 2, 1)
        self.tableWidget.setSpan(0, 3, 2, 1)
        self.tableWidget.setSpan(0, 4, 1, 5)
        self.tableWidget.setSpan(0, 9, 1, 2)
        self.tableWidget.setSpan(0, 11, 1, 10) #9
        self.tableWidget.setSpan(0, 21, 2, 1)
        self.tableWidget.setSpan(0, 22, 2, 1)
        self.tableWidget.setSpan(0, 23, 2, 1)
        self.tableWidget.setSpan(0, 24, 2, 1)

        # 设置列名
        self.checkbox = QCheckBox()
        self.tableWidget.setCellWidget(0, 0, self.checkbox)
        self.tableWidget.setItem(0, 1, QTableWidgetItem("序号"))
        self.tableWidget.item(0, 1).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(0, 2, QTableWidgetItem("站点"))
        self.tableWidget.item(0, 2).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(0, 3, QTableWidgetItem("录入组"))
        self.tableWidget.item(0, 3).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(0, 4, QTableWidgetItem("基础信息"))
        self.tableWidget.item(0, 4).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(0, 9, QTableWidgetItem("问题信息"))
        self.tableWidget.item(0, 9).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(0, 11, QTableWidgetItem("回电状态"))
        self.tableWidget.item(0, 11).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(0, 21, QTableWidgetItem("短信状态"))
        self.tableWidget.item(0, 21).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(0, 22, QTableWidgetItem("机器人状态"))
        self.tableWidget.item(0, 22).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(0, 23, QTableWidgetItem("人工状态"))
        self.tableWidget.item(0, 23).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(0, 24, QTableWidgetItem("id"))
        self.tableWidget.item(0, 24).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)

        self.tableWidget.setItem(1, 4, QTableWidgetItem("类型"))
        self.tableWidget.item(1, 4).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 5, QTableWidgetItem("来电号码"))
        self.tableWidget.item(1, 5).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 6, QTableWidgetItem("运单号"))
        self.tableWidget.item(1, 6).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 7, QTableWidgetItem("来电时间"))
        self.tableWidget.item(1, 7).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 8, QTableWidgetItem("收货地址"))
        self.tableWidget.item(1, 8).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 9, QTableWidgetItem("问题类型"))
        self.tableWidget.item(1, 9).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 10, QTableWidgetItem("问题描述"))
        self.tableWidget.item(1, 10).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 11, QTableWidgetItem("第一次回电结果"))
        self.tableWidget.item(1, 11).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 12, QTableWidgetItem("第一次回电时间"))
        self.tableWidget.item(1, 12).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 13, QTableWidgetItem("第一次接通时长"))
        self.tableWidget.item(1, 13).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 14, QTableWidgetItem("第二次回电结果"))
        self.tableWidget.item(1, 14).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 15, QTableWidgetItem("第二次回电时间"))
        self.tableWidget.item(1, 15).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 16, QTableWidgetItem("第二次接通时长"))
        self.tableWidget.item(1, 16).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 17, QTableWidgetItem("第三次回电结果"))
        self.tableWidget.item(1, 17).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 18, QTableWidgetItem("第三次回电时间"))
        self.tableWidget.item(1, 18).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 19, QTableWidgetItem("第三次接通时长"))
        self.tableWidget.item(1, 19).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setItem(1, 20, QTableWidgetItem("异常情况"))
        self.tableWidget.item(1, 20).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.tableWidget.setColumnHidden(24,True) #隐藏id列
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableWidget.horizontalHeader().setSectionResizeMode(8, QHeaderView.Interactive)#自定义列宽
        self.tableWidget.setColumnWidth(8, 300)#自定义列宽的宽距
        self.tableWidget.horizontalHeader().setSectionResizeMode(10, QHeaderView.Interactive)  # 自定义列宽
        self.tableWidget.setColumnWidth(10, 300)  # 自定义列宽的宽距
        self.verticalLayout.addWidget(self.tableWidget)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_7 = QtWidgets.QLabel(self.centralWidget)
        self.label_7.setObjectName("label_7")
        self.horizontalLayout_3.addWidget(self.label_7)
        spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem5)
        self.pushButton_6 = QtWidgets.QPushButton(self.centralWidget)  # 配置
        self.pushButton_6.setObjectName("pushButton_6")
        self.horizontalLayout_3.addWidget(self.pushButton_6)
        self.pushButton_5 = QtWidgets.QPushButton(self.centralWidget)  # 通话记录
        self.pushButton_5.setObjectName("pushButton_5")
        self.horizontalLayout_3.addWidget(self.pushButton_5)
        self.pushButton_4 = QtWidgets.QPushButton(self.centralWidget)  # 自动刷新
        self.pushButton_4.setObjectName("pushButton_4")
        self.horizontalLayout_3.addWidget(self.pushButton_4)
        self.pushButton_3 = QtWidgets.QPushButton(self.centralWidget)  # 完成
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout_3.addWidget(self.pushButton_3)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        MainWindow.setCentralWidget(self.centralWidget)

        #点击事件
        self.pushButton_2.clicked.connect(self.Select_file)
        self.comboBox_2.currentTextChanged.connect(self.comboBox2_changed)
        self.comboBox_3.currentTextChanged.connect(self.read_tickt)
        self.pushButton.clicked.connect(self.query_tickt)
        self.pushButton_3.clicked.connect(self.update_ticket)
        self.checkbox.stateChanged.connect(self.HorSectionClicked)
        self.pushButton_4.clicked.connect(self.refresh_event)
        self.pushButton_5.clicked.connect(self.select_callnub)
        self.pushButton_6.clicked.connect(self.setting)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "百世快递工具"))
        self.pushButton_2.setText(_translate("MainWindow", "导入"))
        self.pushButton_4.setText(_translate("MainWindow", "自动刷新"))
        self.pushButton_5.setText(_translate("MainWindow", "通话记录"))
        self.pushButton_6.setText(_translate("MainWindow", "任务配置"))
        self.label.setText(_translate("MainWindow", "开始日期："))
        self.label_5.setText(_translate("MainWindow", "结束日期："))
        self.label_3.setText(_translate("MainWindow", "单号："))
        self.label_6.setText(_translate("MainWindow", "人工跟进状态："))
        self.label_7.setText(_translate("MainWindow", "数据"))
        self.label_2.setText(_translate("MainWindow", "录入组："))
        self.label_4.setText(_translate("MainWindow", "状态："))
        self.comboBox.addItems(["全部","已完成","未处理"])
        self.comboBox_4.addItems(["全部", "站点组", "前台组"])
        self.comboBox_5.addItems(["全部","已跟进","未跟进"])
        self.pushButton.setText(_translate("MainWindow", "查询"))
        self.pushButton_3.setText(_translate("MainWindow", "完成"))
        if not self.user_info:
            QMessageBox.information(self,"提示","请导入用户信息",QMessageBox.Yes)
        self.read_userdb()

        # 将当前时间输出到文本框
    def handleDisplay(self):
        self.read_tickt()

    def refresh_event(self):
        button = self.pushButton_4.text()
        if button == "自动刷新":
            self.pushButton_4.setText("取消自动刷新")
            # 定时刷新
            if self.backend is None:
                self.backend = BackendThread()
            # 连接信号
            self.backend.update_date.connect(self.handleDisplay)
            if self.thread is None:
                self.thread = QtCore.QThread()
                self.backend.moveToThread(self.thread)
                self.thread.started.connect(self.backend.run)
                # 开始线程
                self.thread.start()
        else:
            self.pushButton_4.setText("自动刷新")
            # self.thread.terminate()
            # self.thread.quit()
            # self.thread.started.disconnect(self.backend.run)
            self.backend.update_date.disconnect(self.handleDisplay)

    #重写键盘监控方法
    def keyPressEvent(self, event):  # 重写键盘监听事件
        # 监听 CTRL+C 组合键，实现复制数据到粘贴板
        if (event.key() == QtCore.Qt.Key_C) and QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:
            text = self.selected_tb_text()  # 获取当前表格选中的数据
            if text:
                pyperclip.copy(text)  # 复制数据到粘贴板

    #更新客户跟进状态 #todo
    def update_ticket(self):
        # col_num = self.tableWidget.columnCount()-1 # 获取当前的列数
        row_num = self.tableWidget.rowCount()
        update_list =[]
        for box,row in zip(self.all_header_combobox,list(range(2,row_num))):
            if box.checkState() == QtCore.Qt.Checked:
                #此行运单
                update_list.append(self.tickt_data[row-2][-1])
        headers = {'Content-Type': 'application/json'}
        requests.post("http://193.112.1.68:8905/order/artificial", data=json.dumps(update_list), headers=headers)


        self.read_tickt()

    #复选框全选
    def HorSectionClicked(self, index):
        # 如果行表头复选框为勾选状态
        if index:
            # 将所有的复选框都设为勾选状态
            for item in self.all_header_combobox:
                item.setCheckState(QtCore.Qt.Checked)
        else:
            for item in self.all_header_combobox:
                item.setCheckState(QtCore.Qt.Unchecked)

    #处理选中的表数据
    def selected_tb_text(self):
        try:
            indexes = self.tableWidget.selectedIndexes()  # 获取表格对象中被选中的数据索引列表
            indexes_dict = {}
            for index in indexes[1:]:  # 遍历每个单元格
                row, column = index.row(), index.column()  # 获取单元格的行号，列号
                if row in indexes_dict.keys():
                    indexes_dict[row].append(column)
                else:
                    indexes_dict[row] = [column]
            # 将数据表数据用制表符(\t)和换行符(\n)连接，使其可以复制到excel文件中
            text = ''
            for row, columns in indexes_dict.items():
                row_data = ''
                for column in columns:
                    data = self.tableWidget.item(row, column).text()
                    if row_data:
                        row_data = row_data + ' ' + data
                    else:
                        row_data = data
                if text:
                    text = text + '\n' + row_data
                else:
                    text = row_data
            return text
        except BaseException as e:
            print(e)
            return ''

    def comboBox2_changed(self): #todo
        combobox2 = self.comboBox_2.currentText().split("------")[0]#用户名
        self.comboBox_3.clear()
        data = self.db.user_site_select(combobox2)
        self.comboBox_3.addItem("全部")
        if data:
            for i in data:
                self.comboBox_3.addItem(i[2])

    # 单号查询 #todo
    def query_tickt(self):
        start_time = self.dateEdit.text()  # 开始时间
        Input_group = self.comboBox_4.currentText()  # 录入号
        status = self.comboBox.currentText()  # 状态
        Odd_Numbers = self.lineEdit_3.text()  # 运单号
        username = self.comboBox_2.currentText().split("------")[0]  # 账号
        site = self.comboBox_3.currentText()  # 站点
        artificial_status = self.comboBox_5.currentText()  # 人工跟进状态
        end_time = self.dateEdit_2.text()  # 结束时间

        headers = {'Content-Type': 'application/json'}

        if Odd_Numbers:
            datas = {"userName": username,
                     "site": site,
                     "trackingNumber": Odd_Numbers,
                     "inputGroup": Input_group,
                     "baseCallTimeStart": start_time,
                     "baseCallTimeEnd": end_time,
                     "artificialStatus": artificial_status,
                     "robotStatus": status,
                     "pageSize": 99999
                     }

        else:
            datas = {"userName": username,
                     "site": site,
                     "inputGroup": Input_group,
                     "baseCallTimeStart": start_time,
                     "baseCallTimeEnd": end_time,
                     "artificialStatus": artificial_status,
                     "robotStatus": status,
                     "pageSize": 99999
                     }

        for i in datas.keys():
            if datas[i] == "全部":
                datas[i] = None


        response = requests.post("http://193.112.1.68:8905/order/query", data=json.dumps(datas),headers=headers)

        info_datas = json.loads(response.text)["content"]

        self.tickt_data = self.db.ticket_td(info_datas)
        self.tableWidget.setRowCount(len(self.tickt_data) + 2)
        self.tickt_display()

    #查寻tickt数据 #todo
    def read_tickt(self):
        combobox2 = self.comboBox_2.currentText().split("------")[0]#用户名
        combobox3 = self.comboBox_3.currentText()#站点
        start_time = self.dateEdit.text()#开始时间
        end_time = self.dateEdit_2.text()#结束时间

        headers = {'Content-Type': 'application/json'}

        if not combobox3=="全部":
            datas = {"userName": combobox2,
                     "site": combobox3,
                     "baseCallTimeStart": start_time,
                     "baseCallTimeEnd": end_time,
                     "robotStatus": None,
                     "pageSize": 99999
                     }
        else:
            datas = {"userName": combobox2,
                     "site": None,
                     "baseCallTimeStart": start_time,
                     "baseCallTimeEnd": end_time,
                     "robotStatus": None,
                     "pageSize": 99999
                     }


        response = requests.post("http://193.112.1.68:8905/order/query", data=json.dumps(datas),headers=headers)
        info_datas = json.loads(response.text)["content"]

        self.tickt_data = self.db.ticket_td(info_datas)
        self.tableWidget.setRowCount(len(self.tickt_data) + 2)
        self.tickt_display()

    #详细信息显示  #todo
    def tickt_display(self):
        error_row_list =[]
        self.all_header_combobox=[]
        x = 2
        self.label_7.setText("共{}条".format(len(self.tickt_data)))
        for i in self.tickt_data:
            y = 1
            checkbox = QCheckBox()
            # 将所有的复选框都添加到 全局变量 all_header_combobox 中
            self.all_header_combobox.append(checkbox)
            # 为每一行添加复选框
            self.tableWidget.setCellWidget(x, 0, checkbox)
            # 为每一行添加序号
            self.tableWidget.setItem(x, 1,QtWidgets.QTableWidgetItem(str(x-1)))
            self.tableWidget.item(x, 1).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)

            for j in range(len(i)):
                y = y + 1
                str_data=str(i[j]) if i[j] else ""
                if j==18:
                    if str(i[18]) != str(None):
                        error_row_list.append(x)

                self.tableWidget.setItem(x, y, QtWidgets.QTableWidgetItem(str_data))
                self.tableWidget.item(x, y).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)

            x = x + 1

        for i in error_row_list:
            for j in range(1,24):
                self.tableWidget.item(i, j).setForeground(QBrush(QColor(255, 0, 0)))  #异常标红


    #初始化显示
    def read_userdb(self):
        if self.user_info:
            self.comboBox_2.clear()
            user_list=tuple(self.user_info.keys())
            self.user_data=self.db.user_password_select(user_list=user_list)
        if self.user_data:
            for i in self.user_data:
                    if i[3]==1:
                        stuts = "验证成功"
                    elif i[3]==0:
                        stuts = "验证失败"
                    self.comboBox_2.addItem(i[1]+"------"+stuts)

    def Select_file(self):
        if not self.user_info:
            self.open_file()
        else:
            Qb=QMessageBox.information(self,"提示","是否需要重新导入",QMessageBox.Yes | QMessageBox.No)
            if Qb==QMessageBox.Yes:
                self.open_file()

    #读用户导入xlsx
    def open_file(self):
        self.user_info={}
        filename = QFileDialog.getOpenFileName(None, '选择文件', '', 'Excel files(*.xlsx , *.xls)')[0]
        self.lineEdit.setText(filename)
        df = pd.read_excel(r"{}".format(filename))

        self.comboBox_2.blockSignals(True) #切断信号，中间的clear（）才不会导致程序崩溃

        self.comboBox_2.clear()
        df1,df2,df3=df["用户名"], df["密码"],df["站点"]
        for user,password in zip(df1, df2):
            if user not in self.user_info.keys():
                BEST=login.login_verification(user,password)
                self.user_info[str(user)]=[password,BEST]
        self.comboBox_2.addItems(self.user_info.keys())
        for user, password,site in zip(df1, df2,df3):
            data = self.db.user_site_select(user,site)
            if not data:
                self.db.user_site_insert(user,site)
            data_p = self.db.user_password_select(user)
            if not data_p:
                status = 1 if self.user_info[str(user)][1] == "验证成功" else 0
                self.db.user_password_insert(str(user), password,status)
            else:
                status = 1 if self.user_info[str(user)][1] == "验证成功" else 0
                self.db.user_password_update(str(user), password, status)
        self.comboBox_2.clear()
        for i in self.user_info.keys():
            self.comboBox_2.addItem(i+"------"+self.user_info[i][1])
        with open("./userinfo.json", "w", encoding="utf-8") as f:
            f.write(json.dumps(self.user_info, indent=4, ensure_ascii=False))

        self.comboBox_2.blockSignals(False)  # 切断信号，中间的clear（）才不会导致程序崩溃


    #通话查询跳转
    def select_callnub(self,MainWindow):
        username = self.comboBox_2.currentText().split("------")[0]  # 账号
        site = self.comboBox_3.currentText()  # 站点

        form1 = QtWidgets.QDialog()
        ui =call_select_dialog.select_call_Dialog()
        ui.setupUi(form1)
        ui.call_data(username,site)  # 复现数据
        form1.setModal(True)#禁止多开
        form1.show()
        form1.exec_()


    #配置跳转
    def setting(self):

        # 判断有无复现数据
        if os.path.exists("../user_setting/setting.json"):
            with open("../user_setting/setting.json", "r")as f:
                data = json.loads(f.read())

        # 数据处理
        Start_time = data["Start_time"]
        End_time = data["End_time"]
        Emergency_contact = data["Emergency_contact"]
        checkState = data["checkState"]

        #窗口跳转
        form2 = QtWidgets.QDialog()
        ui = user_setting_dialog.setting_Dialog()
        ui.setupUi(form2)
        ui.setting_data(Start_time, End_time, Emergency_contact,checkState,self.scheduler) #复现数据
        form2.setModal(True)
        form2.show()
        form2.exec_()


    def showDialog(self):
        user_name_list = list(self.user_info.keys())
        user_name_list.append('test')
        dialog = alert_dialog.alert_dialog()
        dialog.show(user_name_list)


class BackendThread(QtCore.QObject):
    # 通过类成员对象定义信号
    update_date = QtCore.pyqtSignal(str)

    # 处理业务逻辑
    def run(self):
        while True:
            data = QtCore.QDateTime.currentDateTime()
            currTime = data.toString("yyyy-MM-dd hh:mm:ss")
            self.update_date.emit(str(currTime))
            time.sleep(30)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ui = Ui_Model_Window()
    ui.showMaximized()
    ui.show()
    #
    # import threading
    # t = threading.Thread(target=showDialog)
    # t.start()

    sys.exit(app.exec_())

